<template>
	<div class="top">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Classification">课程管理</a>
			</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Classification">分类管理</a>
			</el-breadcrumb-item>
		</el-breadcrumb>
	</div>

	<div class="middel">
		<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
			<el-form-item label="课程分类名称">
				<el-input v-model="queryInfo. classifyName" placeholder="请输入课程分类名称" clearable />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="search">搜索</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="success" @click="openDialog('add')">新增课程分类</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="batchDelete" :disabled="multipleSelection.length === 0">
					批量删除
				</el-button>
			</el-form-item>
		</el-form>
	</div>

	<div class="content">
		<el-table
			ref="multipleTableRef"
			:data="tableData"
			row-key="id"
			style="width: 100%"
			@selection-change="handleSelectionChange"
			:loading="loading"
			border
			stripe
			class="category-table"
		>
			<el-table-column type="selection" width="55" />
			<el-table-column prop="id" label="ID" width="100" align="center" />
      <!-- 在表格的“ID”列和“课程分类名称”列之间插入 -->
      <el-table-column label="分类图标" width="180" align="center">
        <template #default="scope">
          <!-- 显示图片，若没有图标则显示默认占位图 -->
          <el-image
            :src="`${scope.row.classifyIcon}`"
            fit="cover"
            width="60"
            height="60"
            :alt="scope.row.classifyName + '的图标'"
          >
            <!-- 图片加载失败/无图标的占位内容 -->
            <template #error>
              <div class="image-placeholder">无图标</div>
            </template>
          </el-image>
        </template>
      </el-table-column>
			<el-table-column prop="classifyName" label="课程分类名称" min-width="200" align="center" show-overflow-tooltip />
			<el-table-column label="操作" width="300" align="center">
				<template #default="scope">
					<div style="display: flex; justify-content: center; gap: 16px;">
						<el-button size="small" type="primary" @click="openDialog('edit', scope.row)">编辑</el-button>
						<el-button size="small" type="danger" @click="deleteCategory(scope.row.id)">删除</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="queryInfo.pageNum"
			:page-sizes="[5, 10, 15, 20]"
			:page-size="queryInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			style="margin-top: 20px"
		/>
	</div>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" width="400">
    <el-form :model="form" label-width="100px" class="dialog-form">
      <el-form-item label="分类名称" required>
        <el-input v-model="form.classifyName" autocomplete="off" maxlength="30" show-word-limit />
      </el-form-item>

      <!-- 对齐且美观的上传区域 -->
      <el-form-item label="分类图标" required class="form-item-align" >
        <el-upload
          class="avatar-uploader"
          :action=" baseURL+'upload'"
          :show-file-list="false"
          :on-success="handleIconUploadSuccess"
          :before-upload="beforeIconUpload"
          name="file"
        >
          <!-- 上传成功后显示图片 -->
          <img v-if="form.classifyIcon" :src="`${form.classifyIcon}`" class="avatar" />
          <!-- 未上传时显示默认图标 -->
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <div class="upload-hint">支持JPG/PNG，建议100x100px，不超过2MB</div>
      </el-form-item>
    </el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';  // 新增：导入Plus图标
import http from '@/util/http';
	const baseURL = http.defaults.baseURL

// 查询参数
const queryInfo = reactive({
	id: '',
  classifyName: '',
	pageSize: 10,
	pageNum: 1
});

// 表格数据和分页
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 选择相关
const multipleTableRef = ref<TableInstance>();


const axios = getCurrentInstance().appContext.config.globalProperties.axios;

// 弹窗表单
const dialogVisible = ref(false);
const dialogTitle = ref('新增课程分类');
const form = reactive({
	id: '',
  classifyName: '',
  classifyIcon: ''
});
const dialogMode = ref("add")

// 查询列表
const queryDataList = () => {
	loading.value = true;
	axios.get('courseClassify/all', {
		params: queryInfo
	})
	.then((response) => {
		if (response && response.code === 200) {
			tableData.value = response.data.list || [];
			total.value = response.data.total || 0;
		} else {
			ElMessage.error(response.message || '查询失败');
		}
	})
	.catch(() => {
		ElMessage.error('网络请求错误，请检查网络连接或服务器状态');
	})
	.finally(() => {
		loading.value = false;
	});
};

onMounted(() => {
	queryDataList();
});

// 搜索
const search = () => {
	queryInfo.pageNum = 1;
	queryDataList();
};

// 分页
const handleSizeChange = (size: number) => {
	queryInfo.pageSize = size;
	queryDataList();
};
const handleCurrentChange = (num: number) => {
	queryInfo.pageNum = num;
	queryDataList();
};


// 打开弹窗
function openDialog(mode: 'add' | 'edit', row?: any) {
	dialogMode.value = mode;
	if (mode === 'add') {
		dialogTitle.value = '新增课程分类';
		form.id = '';
		form.classifyName = '';
    form.classifyIcon = '';
	} else if (mode === 'edit' && row) {
		dialogTitle.value = '编辑课程分类';
		form.id = row.id;
		form.classifyName = row.classifyName;
    form.classifyIcon = row.classifyIcon
	}
	dialogVisible.value = true;
}
// 3. 图片上传成功回调：保存后端返回的图片URL到表单
const handleIconUploadSuccess = (response) => {
  // 假设后端返回格式：{ code: 200, data: { url: "https://xxx.png" } }
  if (response.code === 200) {
    console.log(response)
    form.classifyIcon = response.data;  // 将上传后的URL绑定到表单
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('上传失败：' + (response.message || '未知错误'));
  }
};

// 4. 上传前校验（限制格式和大小）
const beforeIconUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;  // 限制2MB以内

  if (!isImage) ElMessage.error('请上传JPG/PNG格式的图片');
  if (!isLt2M) ElMessage.error('图片大小不能超过2MB');

  return isImage && isLt2M;  // 校验通过才允许上传
};

// 新增/编辑提交
function submitForm() {
  console.log(66666);

	if (!form.classifyName.trim()) {
		ElMessage.warning('请输入分类名称');
		return;
	}
	if (dialogMode.value === 'add') {
    console.log(form);
		axios.post('/courseClassify', {
      classifyName: form.classifyName,
      classifyIcon:form.classifyIcon
		}).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('新增成功');
				dialogVisible.value = false;
				queryDataList();
			} else {
				ElMessage.error(resp.message || '新增失败');
			}
		});
	} else if (dialogMode.value === 'edit') {
		axios.put('/courseClassify', {
			id: form.id,
      classifyName: form.classifyName,
      classifyIcon:form.classifyIcon
		}).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('编辑成功');
				dialogVisible.value = false;
				queryDataList();
			} else {
				ElMessage.error(resp.message || '编辑失败');
			}
		});
	}
}

// 删除
function deleteCategory(id: number) {
	ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
		type: 'warning'
	}).then(() => {
		axios.delete(`/courseClassify/${id}`).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('删除成功');
				queryDataList();
			} else {
				ElMessage.error(resp.message || '删除失败');
			}
		});
	});
}
const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
	}
// 批量删除
function batchDelete() {
	ElMessageBox.confirm(
			'确定要删除此课程吗？',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(() => {
			axios.delete(`courseClassify/`, {
				params: {
					ids: multipleSelection.value.join(',')
				}
			}).then((resp) => {
				if (resp.code == 200) {
					queryDataList();
					ElMessage.success('删除成功');
				} else {
					ElMessage.error('删除失败');
					console.log(multipleSelection.value);
				}
			}).catch(error => {
				console.error('Error:', error);
				ElMessage.error('请求出错，请重试');
			})
		}).catch(() => {
			// 用户取消操作
		})
}
</script>

<style scoped>
.top {
	background-color: #f8f9fa;
	padding: 12px 20px;
	margin-bottom: 15px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.middel {
	background: #fff;
	padding: 20px;
	margin-bottom: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.demo-form-inline {
	display: flex;
	align-items: center;
	gap: 15px;
}
.demo-form-inline .el-form-item {
	margin-right: 20px;
}
.demo-form-inline .el-input,
.demo-form-inline .el-select {
	width: 220px;
}

.el-button + .el-button {
	margin-left: 10px;
}
.content {
	background: #fff;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.category-table {
	background: #fff;
	border-radius: 8px;
}

.dialog-form {
	padding-top: 10px;
}
.image-placeholder {
  width: 60px;
  height: 60px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #999;
}
/* 上传按钮和图片的样式 */
.avatar-uploader {
  margin-bottom: 10px;
}

/* 图片样式 */
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 6px; /* 圆角 */
  border: 1px solid #eee; /* 轻微边框 */
  object-fit: cover;
}

/* 未上传时的图标区域 */
.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  border: 2px dashed #ccc; /* 虚线边框 */
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #666;
  background-color: #f9f9f9;
  transition: all 0.2s; /*  hover动画 */
}

/* 鼠标悬停效果 */
.avatar-uploader-icon:hover {
  border-color: #409eff; /* 主题色边框 */
  color: #409eff; /* 主题色图标 */
}

/* 提示文字样式 */
.upload-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: center; /* 提示文字居中 */
}

/* 调整表单整体间距 */
.dialog-form {
  padding: 10px 0;
}

/* 优化弹窗内边距 */



</style>